#include "execution/execution_types.h"
#include "execution/position_manager.h"
#include <iostream>
#include <sstream>
#include <chrono>

namespace hft {

PositionManager::PositionManager() {
}

void PositionManager::onTrade(const Trade& trade) {
    updatePosition(trade);
}

void PositionManager::updateLastPrice(const std::string& symbol, double price) {
    if (price <= 0) return;
    
    // 更新所有相关持仓的最新价格
    for (auto& [key, position] : positions_) {
        if (position.symbol == symbol) {
            position.updateLastPrice(price);
            notifyPositionUpdate(position);
        }
    }
}

void PositionManager::updateLastPrices(const std::unordered_map<std::string, double>& prices) {
    for (const auto& [symbol, price] : prices) {
        updateLastPrice(symbol, price);
    }
}

void PositionManager::calculateUnrealizedPnL(const std::unordered_map<std::string, double>& last_prices) {
    for (auto& [key, position] : positions_) {
        auto it = last_prices.find(position.symbol);
        if (it != last_prices.end()) {
            position.updateLastPrice(it->second);
            notifyPositionUpdate(position);
        }
    }
}

void PositionManager::updateMarginRatio(const std::string& symbol, double margin_ratio) {
    if (margin_ratio <= 0) return;
    
    margin_ratios_[symbol] = margin_ratio;
    
    // 更新所有相关持仓的保证金
    for (auto& [key, position] : positions_) {
        if (position.symbol == symbol) {
            position.updateMargin(margin_ratio);
            notifyPositionUpdate(position);
        }
    }
}

Position* PositionManager::getPosition(const std::string& symbol, const std::string& account, const std::string& strategy_id) {
    std::string key = generatePositionKey(symbol, account, strategy_id);
    auto it = positions_.find(key);
    if (it != positions_.end()) {
        return &it->second;
    }
    return nullptr;
}

std::vector<Position*> PositionManager::getAccountPositions(const std::string& account) {
    std::vector<Position*> result;
    for (auto& [key, position] : positions_) {
        if (position.account == account) {
            result.push_back(&position);
        }
    }
    return result;
}

std::vector<Position*> PositionManager::getStrategyPositions(const std::string& strategy_id) {
    std::vector<Position*> result;
    for (auto& [key, position] : positions_) {
        if (position.strategy_id == strategy_id) {
            result.push_back(&position);
        }
    }
    return result;
}

std::vector<Position*> PositionManager::getSymbolPositions(const std::string& symbol) {
    std::vector<Position*> result;
    for (auto& [key, position] : positions_) {
        if (position.symbol == symbol) {
            result.push_back(&position);
        }
    }
    return result;
}

const std::unordered_map<std::string, Position>& PositionManager::getAllPositions() const {
    return positions_;
}

void PositionManager::settle() {
    // 日终清算，将今仓转为昨仓
    for (auto& [key, position] : positions_) {
        position.history_volume = position.today_volume;
        position.history_avg_price = position.today_avg_price;
        position.today_volume = 0;
        position.today_avg_price = 0.0;
        
        // 重置开平仓统计
        position.open_volume = 0;
        position.open_amount = 0.0;
        position.close_volume = 0;
        position.close_amount = 0.0;
        
        // 已实现盈亏清零
        position.realized_pnl = 0.0;
        
        // 更新时间
        position.update_time = std::chrono::system_clock::now();
        
        notifyPositionUpdate(position);
    }
}

void PositionManager::registerPositionCallback(std::function<void(const Position&)> callback) {
    position_callback_ = callback;
}

std::string PositionManager::generatePositionKey(const std::string& symbol, const std::string& account, const std::string& strategy_id) {
    std::stringstream ss;
    ss << symbol << ":" << account << ":" << strategy_id;
    return ss.str();
}

void PositionManager::updatePosition(const Trade& trade) {
    std::string key = generatePositionKey(trade.symbol, trade.account, trade.strategy_id);
    
    // 如果持仓不存在，创建新持仓
    if (positions_.find(key) == positions_.end()) {
        Position position;
        position.symbol = trade.symbol;
        position.account = trade.account;
        position.strategy_id = trade.strategy_id;
        position.create_time = std::chrono::system_clock::now();
        
        // 设置保证金率
        auto it = margin_ratios_.find(trade.symbol);
        if (it != margin_ratios_.end()) {
            position.margin_ratio = it->second;
        }
        
        positions_[key] = position;
    }
    
    // 更新持仓
    positions_[key].updatePosition(trade);
    
    // 通知持仓更新
    notifyPositionUpdate(positions_[key]);
}

void PositionManager::notifyPositionUpdate(const Position& position) {
    if (position_callback_) {
        position_callback_(position);
    }
}

} // namespace hft